#!/bin/bash

# 1. 清除所有celery线程
# echo "Stopping all celery processes..."
# ps aux | grep "celery" | grep -v grep | awk '{print $2}' | xargs kill -9

echo "Stopping all celery processes..."
ps aux | grep "celery" | grep -v grep | awk '{print $2}' | xargs -r kill -9



# 清除celery日志
echo "Clearing celery log..."
CELERY_LOG_PATH="/root/autodl-tmp/rope/celery.log"
if [ -f "$CELERY_LOG_PATH" ]; then
    > $CELERY_LOG_PATH
fi

# 2. 结束运行在6006端口上的进程
echo "Stopping processes on port 6006..."
PID=$(lsof -t -i :6006)
if [[ ! -z $PID ]]; then
    echo "Killing process on port 6006 with PID: $PID"
    kill -9 $PID
fi

# 清空日志文件
LOG_PATH="/root/autodl-tmp/rope/fastapi.log"
echo "Clearing log file at $LOG_PATH..."
if [ -f "$LOG_PATH" ]; then
    > $LOG_PATH
fi

# 解析-c参数来获取Celery线程数，如果未提供，则默认为12
PROC_COUNT=12
while getopts ":c:" opt; do
    case $opt in
        c) PROC_COUNT="$OPTARG"
        ;;
        \?) echo "Invalid option -$OPTARG" >&2
        ;;
    esac
done

# 切换目录并启动python程序
cd /root/autodl-tmp/rope
echo "Starting the python script with $PROC_COUNT threads..."
python main.py -c $PROC_COUNT
